package com.hly.versioncontroladmin.controller;


import com.hly.versioncontroladmin.domain.VcCategory;
import com.hly.versioncontroladmin.domain.VcVersion;
import com.hly.versioncontroladmin.domain.Vo.UploadFileVo;
import com.hly.versioncontroladmin.result.Code;
import com.hly.versioncontroladmin.result.Result;
import com.hly.versioncontroladmin.service.VcApplicationService;
import com.hly.versioncontroladmin.service.VcCategoryService;
import com.hly.versioncontroladmin.service.VcVersionService;
import com.hly.versioncontroladmin.utils.IPUtils;
import com.hly.versioncontroladmin.utils.PathUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.util.HashMap;

@RestController
@RequestMapping("/api/file")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FileController {

    private final IPUtils ipUtils;
    private final PathUtils pathUtils;
    private final VcApplicationService applicationService;
    private final VcVersionService versionService;

    @PostMapping("/upload")
    public Result upload(MultipartFile file, @RequestParam(value = "vcVersion") Integer vcVersion,
                         @RequestParam(value = "appId") String appId){

        String url = "";

        if (applicationService.getById(appId) == null){
            Code.BUSINESS_ERR("不存在该应用");
        }

        VcVersion newAppVersion = versionService.getNewAppVersion(appId);

        if (newAppVersion != null && vcVersion <= newAppVersion.getVcVersion()){
            Code.BUSINESS_ERR("版本号必须大于上一个的版本");
        }

        String originalFilename = file.getOriginalFilename();

        int index = originalFilename.indexOf(".");

        url = "/" + appId + "-" + vcVersion + originalFilename.substring(index);

        try {
            FileOutputStream stream = new FileOutputStream(pathUtils.path + url);
            stream.write(file.getBytes());
            stream.close();
        }catch (Exception e){
            Code.BUSINESS_ERR("上传失败");
        }

        return Result.ok(UploadFileVo.builder()
                .url("http://" + ipUtils.IP + ":" + ipUtils.port + pathUtils.resourcesPath + url)
                .size(file.getSize())
                .suffix(originalFilename.substring(index))
                .build());
    }
}
